import * as FileSystem from "expo-file-system";
import { FFprobeKit, FFmpegKit } from "ffmpeg-kit-react-native";
import { Alert, Platform, Image } from "react-native";
import { Asset } from "expo-asset"; // 用于处理assets资源

// const copyAssetToTemp = async (assetPath) => {
//   // 获取资源在 Android/iOS 中的原始路径
//   const assetUri =
//     Platform.OS === "android"
//       ? `file:///android_asset/${assetPath}`
//       : assetPath;

//   // 生成目标路径（应用文档目录）
//   const filename = assetPath.split("/").pop();
//   const destPath = `${FileSystem.DocumentDirectoryPath}/${filename}`;

//   // 复制文件
//   await FileSystem.copyFile(assetUri, destPath);
//   return destPath;
// };

async function copyWatermarkToDocuments() {
  // const watermarkUri = Image.resolveAssetSource(
  //   require("../assets/images/favicon.png")
  // ).uri;
  // const localPath = `${FileSystem.documentDirectory}favicon.png`;

  // await FileSystem.downloadAsync(watermarkUri, localPath);
  // return watermarkUri;
  // 1. 加载assets中的水印图片
  const watermarkAsset = Asset.fromModule(
    require("../assets/images/favicon.png")
  );
  await watermarkAsset.downloadAsync(); // 确保资源已下载

  // 生产环境下，asset.localUri 可能是资源 ID（如 assets_images_favicon）
  if (!watermarkAsset?.localUri?.startsWith("file://")) {
    // 将资源复制到应用文档目录
    const destUri = `${FileSystem.documentDirectory}favicon.png`;
    await FileSystem.copyAsync({
      from: watermarkAsset.uri, // 原始资源 URI（assets_images_favicon）
      to: destUri, // 目标路径（file://...）
    });
    return destUri; // 返回 file:// 路径
  } else {
    // return watermarkAsset.localUri; // 开发环境直接返回
    // Alert.alert("watermarkAsset", JSON.stringify(watermarkAsset));
    // 2. 获取水印图片的本地路径
    const watermarkUri = watermarkAsset.localUri || watermarkAsset.uri;
    return watermarkUri;
  }
}

// 删除视频中的某个时间段
const removeVideoSegment = async (
  videoUri: string,
  duration: number,
  outputPath: string,
  segmentDuration: number
) => {
  const totalDuration = duration;

  // 2. 如果删除时长大于等于视频总时长，直接返回错误
  if (segmentDuration >= totalDuration) {
    throw new Error("删除时长必须小于视频总时长");
  }

  // 3. 随机生成开始时间
  const maxStartTime = totalDuration - segmentDuration;
  const startTime = Math.random() * maxStartTime;
  const endTime = startTime + segmentDuration;

  // 4. 创建临时文件列表
  const tempListPath = `${FileSystem.cacheDirectory}temp_list.txt`;

  // 5. 构建 concat 命令
  let concatContent = "";

  // 如果开始时间大于0，保留开头部分
  if (startTime > 0) {
    concatContent += `file '${videoUri}'\n`;
    concatContent += `inpoint 0\n`;
    concatContent += `outpoint ${startTime}\n`;
  }

  // 如果结束时间小于总时长，保留结尾部分
  if (endTime < totalDuration) {
    concatContent += `file '${videoUri}'\n`;
    concatContent += `inpoint ${endTime}\n`;
    concatContent += `outpoint ${totalDuration}\n`;
  }
  console.log(concatContent);
  // 6. 写入临时文件列表
  await FileSystem.writeAsStringAsync(tempListPath, concatContent);

  // 7. 执行 concat 命令
  const command = `-f concat -safe 0 -i ${tempListPath} -c copy ${outputPath}`;
  // const result = await FFmpegKit.execute(command);

  // // 8. 清理临时文件
  // await FileSystem.deleteAsync(tempListPath);

  // return result;
  return command;
};

/**
 * 生成视频裁剪命令（输出单个文件）
 * @param inputPath 输入视频路径
 * @param outputPath 输出文件路径
 * @returns 返回FFmpeg命令字符串
 */
async function generateSingleCutCommand(
  inputPath: string,
  outputPath: string
): Promise<string> {
  // 1. 获取视频时长
  const duration = await getVideoDuration(inputPath);

  // 2. 根据时长确定裁剪次数
  const cutsCount = determineCutCount(duration);

  // 3. 生成随机裁剪时间点（避开开头和结尾）
  const cutPoints = generateRandomCutPoints(duration, cutsCount, 1.0); // 每次裁剪1秒

  // 4. 构建FFmpeg命令（输出单个文件）
  return buildSingleOutputCommand(inputPath, outputPath, cutPoints, 1.0);
}

// 获取视频时长
async function getVideoDuration(inputPath: string): Promise<number> {
  const session = await FFprobeKit.getMediaInformation(inputPath);
  const information = await session.getMediaInformation();
  return information.getDuration(); // 返回秒数
}

// 根据视频时长确定裁剪次数
function determineCutCount(duration: number): number {
  if (duration > 600) return 15; // 10分钟以上裁剪15次
  if (duration > 420) return 10; // 7分钟以上裁剪10次
  if (duration > 180) return 6; // 3分钟以上裁剪6次
  if (duration > 60) return 4; // 1分钟以上裁剪4次
  if (duration > 20) return 2; // 20秒以上裁剪2次
  if (duration > 10) return 1; // 10秒以上裁剪1次
  return 0; // 视频太短不裁剪
}

// 生成随机裁剪时间点（避开开头和结尾）
function generateRandomCutPoints(
  duration: number,
  cutsCount: number,
  cutDuration: number
): number[] {
  const cutPoints: number[] = [];
  const safeDuration = duration - 2 * cutDuration; // 确保不裁剪开头和结尾

  if (cutsCount === 0 || safeDuration <= 0) return cutPoints;

  // 生成随机时间点
  for (let i = 0; i < cutsCount; i++) {
    let randomPoint: number;
    let attempts = 0;
    const minDistance = cutDuration * 2; // 确保裁剪片段间有最小间隔

    do {
      // 在安全范围内随机生成时间点（避开开头和结尾各cutDuration时长）
      randomPoint = cutDuration + Math.random() * safeDuration;
      attempts++;

      // 防止无限循环
      if (attempts > 100) {
        // 如果无法找到合适的位置，就均匀分布
        randomPoint = cutDuration + (i * safeDuration) / cutsCount;
        break;
      }
    } while (
      // 检查新生成的点是否与已有点太接近
      cutPoints.some((point) => Math.abs(point - randomPoint) < minDistance)
    );

    cutPoints.push(randomPoint);
  }

  // 按时间顺序排序
  return cutPoints.sort((a, b) => a - b);
}

// 构建输出单个文件的FFmpeg命令
function buildSingleOutputCommand(
  inputPath: string,
  outputPath: string,
  cutPoints: number[],
  cutDuration: number
): string {
  if (cutPoints.length === 0) {
    return "";
  }

  // 构建复杂滤镜命令
  let filterComplex = "";
  let inputs = "";

  cutPoints.forEach((startTime, index) => {
    inputs += `-ss ${startTime.toFixed(3)} -t ${cutDuration} -i ${inputPath} `;
    filterComplex += `[${index}:v]trim=0:${cutDuration},setpts=PTS-STARTPTS[v${index}];`;
    filterComplex += `[${index}:a]atrim=0:${cutDuration},asetpts=PTS-STARTPTS[a${index}];`;
  });

  // 拼接所有片段
  filterComplex += `${Array.from(
    { length: cutPoints.length },
    (_, i) => `[v${i}][a${i}]`
  ).join("")}`;
  filterComplex += `concat=n=${cutPoints.length}:v=1:a=1[outv][outa]`;

  return `${inputs}-filter_complex "${filterComplex}" -map "[outv]" -map "[outa]" ${outputPath}`;
}

export const getCommand = async (videoUri, outputPath, operation) => {
  const watermarkSize = 100;
  const margin = 10;
  if (operation === "reduce") {
    // const watermarkImagePath = await copyWatermarkToDocuments();
    const duration = await getVideoDuration(videoUri);
    const allDuration = Math.floor(duration - 1 - 3);
    const trimmedDuration = allDuration > 0 ? allDuration : duration;
    const timestamp = new Date().getTime();
    // const combinedCommand1 = `-i ${videoUri} -vf "hue=s=0" -c:a copy ${outputPath}`;
    const combinedCommand =
      `-i ${videoUri} ` +
      // `-i ${watermarkImagePath} -filter_complex "[0]colorbalance=rs=0.2:gs=-0.1:bs=-0.3,drawbox=x=0:y=0:w=iw:h=ih:color=red@1:t=5,scale=iw*0.9:ih*0.9[main];[1]scale=100:-1[wm];[main][wm]overlay=W-w-15:H-h-15" ` +
      // `-vf "hue=s=0" ` +
      // `-vf "scale=iw*0.9:ih*0.9" ` + // 组合调色和缩放滤镜
      // `-c:v libx264 -preset slower -crf 20 -x264-params ref=5 ` + // 高质量重编码
      // `-vf "pad=w=iw+20:h=ih+20:x=10:y=10:color=black" ` +
      // `-filter_complex "drawbox=x=0:y=0:w=iw:h=ih:color=black:t=10" `+
      `-r 24 ` + // 修改帧率
      `-ss 1 ` + // 剪掉开头0.5秒
      (trimmedDuration > 10 ? `-t ${trimmedDuration} ` : "") +
      `-c:v libx264 -preset veryfast -crf 18 -x264-params ref=5  ` +
      `-c:a copy ` + // 保持原始音频
      `${outputPath}`;
    return combinedCommand;
  } else if (operation === "md5") {
    const timestamp = new Date().getTime();
    const command = `-i ${videoUri} -metadata comment="Modified at ${timestamp}" -c:v copy -c:a copy ${outputPath}`;
    return command;
  } else if (operation === "bothProccess") {
    const combinedCommand =
      `-i ${videoUri} ` +
      // `-vf "scale=iw*0.9:ih*0.9" ` + // 组合调色和缩放滤镜
      // `-c:v libx264 -preset slower -crf 20 -x264-params ref=5 ` + // 高质量重编码
      `-r 24 ` + // 修改帧率
      `-ss 0.5 ` + // 剪掉开头0.5秒
      `-c:a copy ` + // 保持原始音频
      `${outputPath}`;
    return combinedCommand;
  }
  return "";
};

export const getOutputPath = (originalUri, suffix) => {
  const originalName = originalUri.split("/").pop();
  const extIndex = originalName.lastIndexOf(".");
  const nameWithoutExt = originalName.substring(0, extIndex);
  const extension = originalName.substring(extIndex);

  const now = new Date();
  const timestamp = `${now.getFullYear()}${(now.getMonth() + 1)
    .toString()
    .padStart(2, "0")}${now.getDate().toString().padStart(2, "0")}_${now
    .getHours()
    .toString()
    .padStart(2, "0")}${now.getMinutes().toString().padStart(2, "0")}`;

  return `${FileSystem.cacheDirectory}${suffix}_${timestamp}_${nameWithoutExt}${extension}`;
};
